'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Sheet, SheetContent, SheetTrigger, SheetHeader, SheetTitle } from '@/components/ui/sheet'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
import { useAuth } from '@/contexts/AuthClientContext'
import {
  BookOpen,
  Menu,
  Bell,
  User,
  Settings,
  MessageCircle,
  X,
  Send,
  Sparkles,
  HelpCircle,
  Lightbulb,
  ArrowRight,
  LogOut
} from 'lucide-react'

const navigation = [
  { name: '首页', href: '/' },
  { name: '项目方向', href: '/courses' },
  { name: '个人画像', href: '/personal-profile' },
  { name: '星途推荐', href: '/recommendation' },
  { name: '个人中心', href: '/profile' }
]

// 根据页面路径获取相关的AI助手提示问题
const getPageQuestions = (pathname: string) => {
  const pageQuestions: { [key: string]: { context: string; questions: string[] } } = {
    '/': {
      context: '首页 - 个人发展系统概览',
      questions: [
        '这个系统是如何帮助我规划专业方向的？',
        '我需要完成哪些步骤才能获得推荐？',
        '测评结果的准确性如何保证？'
      ]
    },
    '/profile/setup': {
      context: '个人信息完善',
      questions: [
        '为什么需要填写这些个人信息？',
        '这些信息如何影响我的专业推荐？',
        '如果我暂时没有相关经历怎么办？'
      ]
    },
    '/questionnaire': {
      context: '专业测评问卷',
      questions: [
        '这些测评题目是基于什么理论设计的？',
        '如何确保我的回答是真实有效的？',
        '测评结果会如何影响我的专业推荐？'
      ]
    },
    '/personal-profile': {
      context: '个人能力画像',
      questions: [
        'K+MAQ能力模型是什么意思？',
        '我的能力分析结果准确吗？',
        '如何根据这个结果改进自己？'
      ]
    },
    '/recommendation': {
      context: '专业方向推荐',
      questions: [
        '帮我设计一下这个项目方向的职业规划',
        '根据课表，做一下大学四年规划',
        '如果我不喜欢推荐的方向怎么办？'
      ]
    },
    '/courses': {
      context: '课程信息查看',
      questions: [
        '这些课程的难度如何？',
        '课程之间的先后顺序重要吗？',
        '如何制定个人学习计划？'
      ]
    },
    '/profile': {
      context: '个人档案管理',
      questions: [
        'K+MAQ能力模型是什么意思？',
        '我的能力分析结果准确吗？',
        '如何根据这个结果改进自己？'
      ]
    },
    '/profile/resume': {
      context: '简历生成和编辑',
      questions: [
        '如何让我的简历更有竞争力？',
        '简历中哪些内容最重要？',
        '如何突出我的专业优势？'
      ]
    }
  }

  return pageQuestions[pathname] || {
    context: '当前页面',
    questions: [
      '我有什么问题可以问你？',
      '能帮我解答一些疑问吗？',
      '这个功能怎么使用？'
    ]
  }
}

interface AppHeaderProps {
  title?: string
  showNavigation?: boolean
}

export function AppHeader({ title, showNavigation = true }: AppHeaderProps) {
  const pathname = usePathname()
  const router = useRouter()
  const { student, logout } = useAuth()
  const [isOpen, setIsOpen] = useState(false)
  const [isMobile, setIsMobile] = useState(false)
  const [isChatOpen, setIsChatOpen] = useState(false)
  const [currentQuestions, setCurrentQuestions] = useState<string[]>([])
  const [currentContext, setCurrentContext] = useState('')

  // 如果是CAS登录页面，隐藏整个头部
  if (pathname === '/cas-login') {
    return null
  }

  // 检测是否为移动端
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth < 768)
    }

    checkIsMobile()
    window.addEventListener('resize', checkIsMobile)

    return () => window.removeEventListener('resize', checkIsMobile)
  }, [])

  // 根据页面路径更新AI助手的问题
  useEffect(() => {
    const pageData = getPageQuestions(pathname||'')
    setCurrentQuestions(pageData.questions)
    setCurrentContext(pageData.context)
  }, [pathname])

  // 处理AI问题点击
  const handleQuestionClick = (question: string) => {
    const params = new URLSearchParams({
      context: currentContext,
      question: question
    })
    router.push(`/chat?${params.toString()}`)
  }

  return (
    <>
      <nav className="border-b bg-background/100  sticky top-0 z-40 bg-white">
        <div className=" px-4 sm:px-6 lg:px-8 w-full">
          <div className="flex justify-between h-16">
            {/* 左侧 Logo 和导航 */}
            <div className="flex items-center space-x-8">
              <Link href="/" className="flex items-center space-x-1">
                <div className="h-8 rounded-lg flex items-center justify-center">
                 <img src="/logo.png" alt=""  className='h-[100%]'/>
                </div>
                <span className="font-bold text-xl hidden sm:inline">
                  { '凯笙小世界'}
                </span>
              </Link>
              
              {/* 桌面端导航 */}
              {showNavigation && (
                <div className="hidden md:flex space-x-6">
                  {navigation.map((item) => (
                    <Link
                      key={item.name}
                      href={item.href}
                      className={cn(
                        "text-sm font-medium transition-colors hover:text-foreground",
                        pathname === item.href || 
                        (item.href !== '/' && pathname?.startsWith(item.href))
                          ? "text-foreground"
                          : "text-muted-foreground"
                      )}
                    >
                      {item.name}
                    </Link>
                  ))}
                </div>
              )}
            </div>

            {/* 右侧用户信息和移动端菜单 */}
            <div className="flex items-center space-x-4">
              {/* 通知按钮 */}
              {/* <Button variant="ghost" size="sm" className="relative">
                <Bell className="w-5 h-5" />
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"></span>
              </Button> */}

              {/* 用户头像下拉菜单 */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="sm" className="hidden sm:flex">
                    <Avatar className="w-8 h-8">
                      <AvatarImage src={student?.avatar || "/placeholder-avatar.jpg"} />
                      <AvatarFallback>{student?.username?.charAt(0) || 'U'}</AvatarFallback>
                    </Avatar>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-56">
                  <div className="flex items-center justify-start gap-2 p-2">
                    <Avatar className="w-8 h-8">
                      <AvatarImage src={student?.avatar || "/placeholder-avatar.jpg"} />
                      <AvatarFallback>{student?.username?.charAt(0) || 'U'}</AvatarFallback>
                    </Avatar>
                    <div className="flex flex-col space-y-1">
                      <p className="text-sm font-medium leading-none">{student?.username || '用户'}</p> 
                      <p className="text-xs leading-none text-muted-foreground">
                        {student?.username || ''}
                      </p>
                    </div>
                  </div>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem asChild>
                    <Link href="/profile" className="cursor-pointer">
                      <User className="mr-2 h-4 w-4" />
                      <span>个人中心</span>
                    </Link>
                  </DropdownMenuItem>

                  <DropdownMenuSeparator />
                  <DropdownMenuItem
                    className="cursor-pointer text-red-600 focus:text-red-600"
                    onClick={logout}
                  >
                    <LogOut className="mr-2 h-4 w-4" />
                    <span>退出登录</span>
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>

              {/* 移动端菜单 */}
              {showNavigation && (
                <Sheet open={isOpen} onOpenChange={setIsOpen}>
                  <SheetTrigger asChild>
                    <Button variant="ghost" size="sm" className="md:hidden">
                      <Menu className="w-5 h-5" />
                    </Button>
                  </SheetTrigger>
                  <SheetContent side="right" className="w-[300px] sm:w-[400px]">
                    <SheetHeader>
                      <SheetTitle>菜单</SheetTitle>
                    </SheetHeader>
                    <div className="flex flex-col space-y-4 mt-8">
                      {/* 用户信息 */}
                      <div className="flex items-center space-x-3 p-4 bg-muted rounded-lg">
                        <Avatar className="w-12 h-12">
                          <AvatarImage src={student?.avatar || "/placeholder-avatar.jpg"} />
                          <AvatarFallback>{student?.username?.charAt(0) || 'U'}</AvatarFallback>
                        </Avatar>
                        <div>
                          <p className="font-medium">{student?.username || '用户'}</p>
                          <p className="text-sm text-muted-foreground">{student?.username || ''}</p>
                        </div>
                      </div>

                      {/* 设置链接 */}
                      <div className="pt-4 border-t space-y-2">
                        <Link
                          href="/profile"
                          onClick={() => setIsOpen(false)}
                          className="flex items-center space-x-3 px-4 py-3 rounded-lg text-sm font-medium hover:bg-muted transition-colors"
                        >
                          <User className="w-4 h-4" />
                          <span>个人中心</span>
                        </Link>
    
                        <button
                          onClick={() => {
                            setIsOpen(false)
                            logout()
                          }}
                          className="flex items-center space-x-3 px-4 py-3 rounded-lg text-sm font-medium hover:bg-muted transition-colors text-red-600 w-full text-left"
                        >
                          <LogOut className="w-4 h-4" />
                          <span>退出登录</span>
                        </button>
                      </div>
                    </div>
                  </SheetContent>
                </Sheet>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* 智能AI助手小窗口 */}
      {showNavigation && pathname !== '/chat' && pathname !== '/cas-login' && (
        <div className={`fixed z-[9999] ${
          isMobile ? 'bottom-[125px] right-4' : 'bottom-6 right-6'
        }`}>
          {!isChatOpen ? (
            /* 收起状态 - 浮动按钮 */
            <div className="flex flex-col items-end">
              {/* 提示气泡 */}
              <div className="mb-2 px-3 py-1 bg-black/80 text-white text-xs rounded-full backdrop-blur-sm opacity-0 hover:opacity-100 transition-opacity duration-300 whitespace-nowrap">
                AI 学习助手 - 点击获取帮助
              </div>

              <Button
                onClick={() => setIsChatOpen(true)}
                size="lg"
                className="w-14 h-14 rounded-full shadow-2xl bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 transition-all duration-300 transform hover:scale-110 relative"
              >
                <span >AI 助手</span>

                {/* 呼吸灯效果 */}

                {/* 新消息提示点 */}
              </Button>
            </div>
          ) : (
            /* 展开状态 - 智能问题窗口 */
            <div className="bg-white rounded-lg shadow-2xl border border-gray-200 w-80 max-w-sm animate-in slide-in-from-bottom-2 duration-300">
              {/* 窗口头部 */}
              <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-blue-500 to-blue-600 rounded-t-lg">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 rounded-full bg-white/20 flex items-center justify-center">
                    <Sparkles className="w-4 h-4 text-white" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-white text-sm">AI学习助手</h3>
                    <p className="text-blue-100 text-xs">{currentContext}</p>
                  </div>
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setIsChatOpen(false)}
                  className="h-6 w-6 p-0 text-white hover:bg-white/20"
                >
                  <X className="w-4 h-4" />
                </Button>
              </div>

              {/* 问题列表 */}
              <div className="p-4">
                <p className="text-sm text-gray-600 mb-3">
                  💡 我可以帮你解答以下问题：
                </p>
                <div className="space-y-2">
                  {currentQuestions.map((question, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      size="sm"
                      onClick={() => handleQuestionClick(question)}
                      className="w-full text-left justify-start text-xs border-blue-200 text-blue-700 hover:bg-blue-50 hover:border-blue-300 transition-colors"
                    >
                      <HelpCircle className="w-3 h-3 mr-2 flex-shrink-0" />
                      <span className="truncate">{question}</span>
                    </Button>
                  ))}
                </div>

                {/* 直接聊天按钮 */}
                <div className="mt-4 pt-3 border-t border-gray-200">
                  <Button
                    onClick={() => {
                      const params = new URLSearchParams({
                        context: currentContext
                      })
                      router.push(`/chat?${params.toString()}`)
                    }}
                    className="w-full bg-blue-500 hover:bg-blue-600 text-white text-sm"
                    size="sm"
                  >
                    <MessageCircle className="w-4 h-4 mr-2" />
                    直接对话
                    <ArrowRight className="w-4 h-4 ml-2" />
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </>
  )
} 